#include "Textures.h"
#include "tga.h"

#include <sstream>

using namespace std;

Textures::Textures()
{
}

void Textures::load()
{
   textureFiles[TEXTURE_CUEBALL] = "img/cue.tga";
   textureFiles[TEXTURE_FIRST_BALL] = "img/1.tga";
   textureFiles[TEXTURE_FIRST_BALL + 1] = "img/2.tga";
   textureFiles[TEXTURE_FIRST_BALL + 2] = "img/3.tga";
   textureFiles[TEXTURE_FIRST_BALL + 3] = "img/4.tga";
   textureFiles[TEXTURE_FIRST_BALL + 4] = "img/5.tga";
   textureFiles[TEXTURE_FIRST_BALL + 5] = "img/6.tga";
   textureFiles[TEXTURE_FIRST_BALL + 6] = "img/7.tga";
   textureFiles[TEXTURE_FIRST_BALL + 7] = "img/8.tga";
   textureFiles[TEXTURE_FIRST_BALL + 8] = "img/9.tga";
   textureFiles[TEXTURE_FIRST_BALL + 9] = "img/10.tga";
   textureFiles[TEXTURE_FIRST_BALL + 10] = "img/11.tga";
   textureFiles[TEXTURE_FIRST_BALL + 11] = "img/12.tga";
   textureFiles[TEXTURE_FIRST_BALL + 12] = "img/13.tga";
   textureFiles[TEXTURE_FIRST_BALL + 13] = "img/14.tga";
   textureFiles[TEXTURE_FIRST_BALL + 14] = "img/15.tga";
   textureFiles[TEXTURE_SHADOW] = "img/shadowGreen.tga";
   textureFiles[TEXTURE_TABLE_SIDES] = "img/tableSides.tga";
   textureFiles[TEXTURE_CORNER_POCKET] = "img/cornerPocket.tga";
   textureFiles[TEXTURE_SIDE_POCKET] = "img/sidePocket.tga";
   textureFiles[TEXTURE_WOOD] = "img/wood.tga";
   
   for (int i = 0; i < TEXTURE_COUNT; i++)
   {
      textures.push_back(loadTexture(textureFiles[i]));  
   }
}

void Textures::useTexture(int texture)
{
   glEnable(GL_TEXTURE_2D);
   glBindTexture(GL_TEXTURE_2D, textures[texture]);
}

GLuint Textures::loadTexture(char *TexName)
{
   TGAImg Img;        // Image loader
   GLuint Texture;

   // Load our Texture
   if(Img.Load(TexName)!=IMG_OK)
      return -1;

   glGenTextures(1,&Texture);            // Allocate space for texture
   glBindTexture(GL_TEXTURE_2D,Texture); // Set our Tex handle as current
   
   // Create the texture
   if(Img.GetBPP()==24)
      glTexImage2D(GL_TEXTURE_2D,0,3,Img.GetWidth(),Img.GetHeight(),0,
                   GL_RGB,GL_UNSIGNED_BYTE,Img.GetImg());
   else if(Img.GetBPP()==32)
      glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,Img.GetWidth(),Img.GetHeight(),0,
                   GL_RGBA,GL_UNSIGNED_BYTE,Img.GetImg());
   else
      return -1;
   
//   // Create the texture
//   if(Img.GetBPP()==24)
//      gluBuild2DMipmaps(GL_TEXTURE_2D,3,Img.GetWidth(),Img.GetHeight(),
//                        GL_RGB,GL_UNSIGNED_BYTE,Img.GetImg());
//   else if(Img.GetBPP()==32)
//      gluBuild2DMipmaps(GL_TEXTURE_2D,4,Img.GetWidth(),Img.GetHeight(),
//                        GL_RGBA,GL_UNSIGNED_BYTE,Img.GetImg());
//   else
//      return -1;   
   
   // Specify filtering and edge actions
   glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
   glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
   glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP);
   glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP);
   
   return Texture;
}

